<template>
  <view class="snowCircle">
    <child-header-bar :childTitle="childTitle" @getMarginTop="getMarginTop"></child-header-bar>
    <view class="snowCircle-content" :style="[{ top: top + 'px' }]">
      <!-- 上传图片或视频-->
      <view class="uploaderBox">
        <uni-file-picker
            v-model="uploaderImgList"
            limit="9"
            title="最多选择9张图片"
            :sourceType="sourceType"
            @select="chooseTheImg"
            @delete="chooseDelete"></uni-file-picker>
      </view>
      <!-- 雪圈标题-->
      <view class="input-title">
        <input v-model="form.title" placeholder="雪圈标题"/>
      </view>
      <!-- 雪圈内容-->
      <view class="input-content">
        <editor-data id="editor"
                     ref="editorData"
                     class="editorStyle"
                     :placeholder-name="placeholder"
                     :editorDetail="form.content"
                     @getContents="getContents()"
                     style="height:auto"></editor-data>
      </view>
      <!-- 雪圈类型-->
      <view class="input-type">
        <text class="input-type_label">发布类型</text>
        <view class="inputTypeBox">
          <uni-data-checkbox class="inputType"
                             mode="tag"
                             multiple
                             v-model="inputCircleType"
                             :localdata="inputTypeList"
                             @change="circleTypeChange"></uni-data-checkbox>
        </view>

      </view>
      <!-- 雪场选择-->
      <view class="input-snowfield" @tap="chooseSnowfield">
        <view class="chooseSnowfieldBox">
          <image class="chooseSnowfieldIcon" mode="scaleToFill" src="../../../static/skiTubing/chooseSnowfieldIcon.png"/>
          <text class="chooseSnowfieldText">{{ slopeName ? slopeName : '雪场选择' }}</text>
        </view>
        <view class="rightIconBox">
          <image class="right_icon" mode="scaleToFill" src="../../../static/skiTubing/right_icon.png"/>
        </view>
      </view>
    </view>
    <view class="snowCircle-bottom">
      <view class="bottom-Icon" @tap="addForm(isModify,'0')">
        <image class="saveDraftIcon" mode="scaleToFill" src="../../../static/skiTubing/saveDraftIcon.png"/>
        <text class="saveDraftText">存草稿</text>
      </view>
      <view class="bottom-Button" @tap="addForm(isModify,'1')" ref="myView">
        <text>分享至雪圈</text>
      </view>
    </view>

    <!-- 雪场选择弹窗-->
    <view class="snowFieldSelectionPopUp" v-if="isShowSnowField" >
      <child-header-bar :childTitle="snowFieldSelectionChildTitle" @getMarginTop="getMarginTop"></child-header-bar>
      <view class="popUp-content" :style="[{ top: top + 'px' }]">
        <uni-search-bar class="snowFieldSearch"
                        radius="50"
                        placeholder="搜索雪场名称"
                        bgColor="#EFF1F4"
                        clearButton="auto"
                        cancelButton="none"
                        @input="snowFieldSearch"></uni-search-bar>
		<scroll-view  scroll-y :style="[{ height: top1 + 'px;border:1px solid #f1f1f1' }]">
	
	<view class="snowFieldListBox">
	  <view class="snowField-item"
	        v-for="(item,index) in snowFieldList"
	        :key="index"
	        @tap="snowFieldName(item)">
	    <view class="item-label"></view>
	    <text class="item-text">
	      {{ item.slopeName }}
	    </text>
	  </view>
	</view>
		  </scroll-view>


      </view>
    </view>
  </view>
</template>

<script>
import UniDataChecklist from '../../../uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox';
import UniFilePicker from '../../../uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker';
import { validate } from '@/utils/validate'
import EditorData from '../../../components/editor/editor';

export default {
  components: {EditorData, UniFilePicker, UniDataChecklist},
  data() {
    return {
      /* 是否修改  0-新增提交 1-修改提交*/
      isModify: 0,
      /* 雪场选择弹窗标题*/
      snowFieldSelectionChildTitle: '雪场选择',
      /* 雪场选择弹窗*/
      isShowSnowField: false,
      /* 页面标题*/
      childTitle: '新建雪圈',
      /* 导航栏高度*/
      top: 150,
      /* 新建雪圈表单*/
      form: {
        /* 当前登录人id*/
        userId: 0,
        /* 雪场id*/
        slopeId: 0,
        /* 标题*/
        title: '',
        /* 标题图多张，或一条短视频*/
        titleImg: '',
        /* 内容*/
        content: '',

        /* 状态(0:保存 1:直接发布)*/
        isShow: '',
        /* 是否为短视频(1:是 0:否)*/
        isVideo: '0',
        /* 雪圈标签分类*/
        circleType: '',
      },
	  
	  content1: '',
      /* 表单校验*/
      rules: {
        /* 雪场id*/
        slopeId: [{ required: true, message: '请选择雪场' }],
        /* 标题*/
        title: [{ required: true, message: '请填写标题' }],
        /* 标题图多张，或一条短视频*/
        titleImg: [{ required: true, message: '请上传图片' }],
        /* 内容*/
        content: [{ required: true, message: '请填写内容' }],
        /* 雪圈标签分类*/
        circleType: [{ required: true, message: '请选择雪圈类型' }],
      },
      /* 富文本默认显示*/
      placeholder: '写点什么呗~\n' + '（文字可换行排版，字数限制500字）',
      /* 雪圈类型*/
      inputTypeList: [],
      /* 已选中雪圈类型数组*/
      inputCircleType: [],
      /* 上传图片文件流*/
      uploaderImgList: [],
      /* 图片上传uni.chooseImage值，从相册选择，拍摄*/
      sourceType: ['album'],

      /* 雪场选择*/
      slopeNameSearch: '',
      snowFieldList: [],
      slopeName: '',

      /* 雪圈修改id*/
      editCircleId: null,
      /* 修改反显数据*/
      editCircleList: [],
      isSuccess:true,
	  top1:0
    };
  },
  onLoad(options) {
    console.log(">>>>options>>>>",options);
    if(options.id){
      /* 修改*/
      this.isModify = 1;
      this.editCircleId = options.id
      this.getEditCircleInfo();
    }else {
      /* 新增*/
      this.isModify = 0;
    }
    this.form.userId = uni.getStorageSync('userId');
    this.getCircleTypeList();
  },
  methods: {
    // 动态接收导航栏高度
    getMarginTop(marginTop) {
      this.top = marginTop ? marginTop : 150;
	  const systemInfo = wx.getSystemInfoSync();
	  
	  // 获取屏幕高度
	  const screenHeight = systemInfo.windowHeight
	  this.top1=screenHeight-marginTop-80
	  console.log(this.top1)
    },

    getContents() {
      let _this = this;
      // console.log("[item.field];>>",this.form[item.field]);
      console.log("this.$refs.editorData>>>",this.$refs.editorData);
      let htmlData = this.$refs.editorData._data.htmlData
      _this.form.content = htmlData
	  _this.content1=this.$refs.editorData._data.htmlData
	console.log('*********',_this.form)
    },
    /* 获取雪圈类型*/
    getCircleTypeList() {
      let _this = this;
      wx.request({
        url: this.$httpApi.install.getCircleType,
        method: 'GET',
        success(res) {
          // console.log("雪圈列表类型>>>>",res.data.data);
          res.data.data.forEach((item, index) => {
            _this.inputTypeList.push({
              text: item.dictLabel,
              value: index,
              valueName: item.dictValue
            });
            // console.log("leixing>>>>",_this.inputTypeList);
          });
        },
      });
    },
    // 选择上传图片
    chooseTheImg(e) {
      console.log('表单字段图片>>>>>>>>>>', this.form.titleImg.split(";"))
      let _this = this;
      e.tempFilePaths.forEach((item, index) => {
        // console.log("循环打印",index, item);
        uni.uploadFile({
          url: _this.$httpApi.install.fileUpload, // 图片上传接口地址
          name: 'file', // 接口参数名
          filePath: item, // 文件路径(接口参数值)
          // 请求成功
          success(res) {
            // console.log('请求成功res>>', res)
            const obj = JSON.parse(res.data);
            _this.uploaderImgList.push({
              url: obj.data.url
            });
            console.log(index + '>>', _this.uploaderImgList);
          },
        });
      });
    },
    // 删除图片
    chooseDelete(err) {
      const num = this.uploaderImgList.findIndex(v => v.url === err.tempFilePath);
      this.uploaderImgList.splice(num, 1);
    },

    // 雪圈类型选择
    circleTypeChange(val) {
      let newTypeList = [];
      val.detail.data.forEach((item, index) => {
        newTypeList.push(item.valueName);
      });
      this.form.circleType = newTypeList.join(',');
    },
    // 雪场选择弹窗
    chooseSnowfield() {
      this.getsnowFieldList();
      this.isShowSnowField = true;
    },
    // 雪场列表
    getsnowFieldList() {
      let _this = this;
      let params = {
        slopeName: this.slopeNameSearch
      };
      // console.log("传参",params);
      wx.request({
        url: this.$httpApi.install.selectListForApp,
        method: 'GET',
        data: params,
        success(res) {
          // console.log("res>>>>",res)
          _this.snowFieldList = res.data.data;
          // console.log("列表数据>>>",_this.snowFieldList);
        },
      });
    },

    // 雪场搜索选择
    snowFieldSearch(e) {
      this.slopeNameSearch = e;
      this.getsnowFieldList();
    },
    // 雪场选择返回
    snowFieldName(item) {
      // console.log("雪场选择返回>>>>",item);
      // console.log("雪场IDD选择返回>>>>",item.slopeId);
      // console.log("雪场shashasha选择返回>>>>",item.slopeName);
      this.slopeName = item.slopeName;
      this.form.slopeId = item.slopeId;
      this.slopeNameSearch = '';
      this.isShowSnowField = false;
    },
    // 提交表单 modify: 0-新增提交 1-修改提交
    //        isShow: 0-存草稿 1-发布
    addForm(modify,isShow) {
      let newImgList = [];
      this.uploaderImgList.forEach(item =>{
        newImgList.push(item.url)
      });
      this.form.titleImg = newImgList.join(";")
      console.log('表单对上传成功图片', this.form.titleImg)
      let _this = this;
      this.form.userId = uni.getStorageSync('userId');
      console.log('this.form.userId>:::>>>', this.form.userId);
      this.form.isShow = isShow;
	  
	  this.form.content=(this.form.content)
	  
	  
      console.log('提交>>>>', this.form);

      if (!validate(_this.form, _this.rules)) return;
      switch (modify) {
        case 0:
          console.log("新增");
          if (_this.isSuccess){
            console.log("新增成功");
            _this.isSuccess = false;
            uni.request({
              url: _this.$httpApi.install.addCircle,
              method: 'POST',
              data: this.form,
              success: (success) => {
                console.log('ok>>', success);
                if (success.data.code === 200) {

                  // 重置新增表单
                  _this.form = {
                    /* 当前登录人id*/
                    userId: 0,
                    /* 雪场id*/
                    slopeId: 0,
                    /* 标题*/
                    title: '',
                    /* 标题图多张，或一条短视频*/
                    titleImg: '',
                    /* 内容*/
                    content: '',
                    /* 状态(0:保存 1:直接发布)*/
                    isShow: '',
                    /* 是否为短视频(1:是 0:否)*/
                    isVideo: '0',
                    /* 雪圈标签分类*/
                    circleType: '',
                  };
                  _this.uploaderImgList = [];
                  uni.showToast({icon: 'success', title: success.data.msg});
                  _this.isSuccess = true;
                  setTimeout(() => {
                    uni.navigateBack({});
                  }, 500);
                }
              },
            });
          }else {
            console.log("没分享成功呢别点了！");
          }
        break;
        case 1:

setTimeout(function() {
    // 在这里写要执行的代码
			console.log('==',_this.form)
			if (_this.isSuccess){
			  _this.form.circleId =  _this.editCircleId
						//this.getContents()
						//this.form.content=_this.form.content
				
			  _this.isSuccess = false;
						console.log('==',this.form)
			  uni.request({
			    url: _this.$httpApi.install.editCircle,
			    method: 'POST',
			    data: _this.form,
			    success: (success) => {
			 
			      if (success.data.code === 200) {
			
			        // 重置新增表单
			        _this.form.circleId = null
			        _this.form = {
			          /* 当前登录人id*/
			          userId: 0,
			          /* 雪场id*/
			          slopeId: 0,
			          /* 标题*/
			          title: '',
			          /* 标题图多张，或一条短视频*/
			          titleImg: '',
			          /* 内容*/
			          content: '',
			          /* 状态(0:保存 1:直接发布)*/
			          isShow: '',
			          /* 是否为短视频(1:是 0:否)*/
			          isVideo: '0',
			          /* 雪圈标签分类*/
			          circleType: '',
			        };
			        _this.uploaderImgList = [];
			        // _this.form.content.undo();
			        uni.showToast({icon: 'success', title: success.data.msg});
			        _this.isSuccess = true;
			        setTimeout(() => {
			          uni.navigateBack({});
			        }, 500);
			      }
			    },
			  });
			}else {
			  console.log("没修改成功呢别点了！");
			}
}, 500);
return

          

        break;
      }



    },
	/*
	setValue(e){
		var value = e;
		const test = /^[\u4E00-\u9FA5A-Za-z0-9-+=_\[\]{};':",./<>?*!@#$%^&`~·！￥……《》？，。/；‘：”【】{}、|]{2,20}$/;
		if(test.test(value)){
		    this.temp.introduce = value;
		}else{
		    var str = value.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "");
		    this.temp.introduce = str
		    return str
		}
	},
	
		*/
    /* 获取需要修改的雪圈信息*/
    getEditCircleInfo(){
      let params = {
        circleId: this.editCircleId
      }

      let _this = this
      wx.request({
        url: this.$httpApi.install.circleDetail,
        method: 'GET',
        data: params,
        success(res) {
          console.log('修改res>>>>', res.data);
          if (res.data.code === 200) {
            console.log('详情数据>>>>>>', res.data.data);
            _this.editCircleList = res.data.data;

            // 修改类型回显
            let circleTypeList = res.data.data.circleType.split(',');
            console.log('circleTypeList>>>>', circleTypeList);
            console.log('_this.inputTypeList', _this.inputTypeList);
            _this.inputTypeList.forEach((option) => {
              circleTypeList.findIndex(item =>{
                if (item === option.valueName) {
                  _this.inputCircleType.push(option.value);
                }
              })
            });
            _this.form.circleType = res.data.data.circleType;
            // 内容回显
            _this.form.content = (res.data.data.content);
            // 雪场名称回显
            _this.form.slopeId = res.data.data.slopeId;
            _this.slopeName = res.data.data.slopeName;
            // 标题回显
            _this.form.title = res.data.data.title
            // 处理图片
            _this.getImage(res.data.data.titleImg);
            _this.form.titleImg = res.data.data.titleImg
          }
        },
      });
    },
    getImage(titleImg){
      let imageList = titleImg.split(";");
      console.log("处理图片>>--",imageList);
      imageList.forEach((item) => {
        this.uploaderImgList.push({
          url: item
        });
      });
      console.log("处理图片结果>>>>------",this.uploaderImgList);
    }
  }

};
</script>

<style lang="scss" scoped>
.snowCircle-content {
  position: absolute;
  width: 100%;
  background-color: #F8FAFE;
  padding: 33rpx 30rpx 0 30rpx;


  // 雪圈标题
  .input-title{
    width: 100%;
    margin-bottom: 40rpx;
    border-bottom:1rpx solid rgba( 145, 164, 178, .3);
    input {
      margin-bottom: 40rpx;
      font-size: 36rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      color: #A4A4A4;
      z-index: 1;
    }

  }

  // 雪圈内容
  .input-content{
    width: 100%;
    margin-bottom: 40rpx;
    border-bottom:1rpx solid rgba( 145, 164, 178, .3);

    .editorStyle {
      width: 100%;
      font-size: 28rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: #A4A4A4;
      box-sizing: border-box;
    }
  }

  // 雪圈类型
  .input-type{
    width: 100%;
    margin-bottom: 35rpx;
    border-bottom:1rpx solid rgba( 145, 164, 178, .3);

    .input-type_label{
      margin-bottom: 30rpx;
      font-size: 24rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: #303030;
    }
    .inputTypeBox{
      margin-bottom: 26rpx;
      .inputType{

        /* 未选中样式*/
        /deep/.is--tag {
          margin-right: 10rpx!important;
          padding: 15rpx 36rpx !important;
          border-radius: 31rpx 31rpx 31rpx 31rpx !important;
          border: none !important;
          background-color: #EFF1F4 !important;
          opacity: 1 !important;
          font-size: 24rpx !important;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400 !important;
          color: #595959 !important;
        }

        /deep/.is--tag:last-child {
          margin-right: 0rpx!important;
        }

        /* 选中样式*/
        /deep/ .is-checked{
          padding: 15rpx 36rpx !important;
          background-color: #303030 !important;
          border-radius: 31rpx 31rpx 31rpx 31rpx !important;
          border: none !important;
          opacity: 1 !important;
          font-size: 24rpx !important;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400 !important;
          color: #88F79C !important;
        }


      }
    }
  }

  // 雪场选择
  .input-snowfield {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 50rpx;
    margin-bottom: 179rpx;
    padding: 0;

    .chooseSnowfieldBox{
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .chooseSnowfieldIcon{
        width: 18rpx;
        height: 20rpx;
        margin-right: 10rpx;
      }

      .chooseSnowfieldText{
        font-size: 24rpx;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        color: #595959;
      }
    }

    .rightIconBox{
      display: flex;
      justify-content: center;
      align-items: center;
      width: 32rpx;
      height: 32rpx;
      border-radius: 50%;
      background: #303030;
      opacity: 1;
      .right_icon{
        width: 20rpx;
        height: 20rpx;
      }
    }

  }
  // 上传图片或视频
  .uploaderBox {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 43rpx;

    .uploaderImg {
      padding:0 10rpx 10rpx 0;
      .uploader_img {
        position: relative;
        z-index: 1;
        width: 223rpx;
        height: 223rpx;
        background: #EFF1F4;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        opacity: 1;
      }

      .iconImg {
        width: 223rpx;
        height: 223rpx;
        background: #EFF1F4;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        opacity: 1;
      }
    }

    .uploaderImg:nth-child(3){
      padding:0 0rpx 10rpx 0;
    }

    .uploaderImg:nth-child(6){
      padding:0 0rpx 10rpx 0;
    }

    .uploaderImg:nth-child(9){
      padding:0 0rpx 10rpx 0;
    }


    .button {
      background: transparent;
      border: none !important;
      box-shadow: none;
      width: 110px;
      padding: 0;
      border-radius: 0;

      image {
        width: 110px;
        height: 110px;
      }
    }
  }

  .uni-uploader__file,
  .uploader_video {
    position: relative;
    z-index: 1;
    width: 200upx;
    height: 200upx;

  }

  .video {
    width: 100%;
    height: 100%;
  }

  .tag-del {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 52rpx;
    height: 52rpx;
    background-color: #D1D1D1;
    border-radius: 50%;
    position: absolute;
    z-index: 22;
    right: 10rpx;
    top: 10rpx;
    .delIcon{
      width: 46rpx;
      height: 46rpx;
    }
  }

  /deep/.uni-uploader__input-box {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    width: 223rpx;
    height: 223rpx;
    background: #EFF1F4;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    opacity: 1;
  }

  .chooseVideoImage{
    width: 182rpx;
    height: 182rpx;
  }
}

.snowCircle-bottom{
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 129rpx;
  background: #FFFFFF;
  border-radius: 0 rpx;
  padding: 0 30rpx;

  .bottom-Icon{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .saveDraftIcon{
      width: 36rpx;
      height: 37rpx;
      margin-bottom: 10rpx;
    }
    .saveDraftText{
      font-size: 20rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: #595959;
    }

  }
  .bottom-Button{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 573rpx;
    height: 88rpx;
    background: #88F79C;
    box-shadow: 0rpx 5rpx 10rpx 1rpx rgba(0,0,0,0.1);
    border-radius: 50rpx 50rpx 50rpx 50rpx;
    opacity: 1;
    font-size: 36rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    color: #303030;
  }

}

// 雪场选择弹窗
.snowFieldSelectionPopUp{
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  width: 100%;

  background-color: rgba(0,0,0,0.1);
  z-index: 999999;

  .popUp-content{
    position: absolute;
    width: 100%;
    background-color: #F8FAFE;
    padding: 23rpx 30rpx 0 30rpx;

    .snowFieldSearch{
      margin-top: 5rpx;
    }

    .snowFieldListBox{
      width: 100%;
      padding: 40rpx 0 0 40rpx;

      .snowField-item{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 100%;
        margin-bottom: 40rpx;

        .item-label{
          width: 14rpx;
          height: 14rpx;
          margin-right: 18rpx;
          background: #A4A4A4;
          border-radius: 50%;
          opacity: 1;
        }
        .item-text{
          font-size: 28rpx;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          color: #A4A4A4;
        }
      }
    }
  }
}
</style>
